/**
 * 点赞记录模型
 * @author HalRui
 * @version 1.0.0
 * @description 管理用户对视频和评论的点赞记录
 * @date 2025年9月27日
 */

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// 点赞记录Schema
const likesSchema = new Schema({
    likeId: {
        type: Number,
        unique: true,
        required: true,
        description: '点赞记录的唯一标识符，自动递增生成'
    },
    
    userId: {
        type: Number,
        required: true,
        index: true,
        description: '点赞用户的ID，关联到用户信息表'
    },
    
    targetType: {
        type: String,
        required: true,
        enum: ['video', 'comment'],
        index: true,
        description: '点赞目标类型，video表示视频，comment表示评论'
    },
    
    targetId: {
        type: Number,
        required: true,
        index: true,
        description: '点赞目标的ID，根据targetType可能是视频ID或评论ID'
    },
    
    likeStatus: {
        type: Number,
        required: true,
        enum: [1, 0, -1],
        default: 1,
        description: '点赞状态，1表示点赞，0表示取消点赞，-1表示点踩'
    },
    
    isDeleted: {
        type: Boolean,
        default: false,
        index: true,
        description: '软删除标记，true表示已删除，false表示正常状态'
    },
    
    deletedAt: {
        type: Date,
        default: null,
        description: '删除时间，记录点赞记录被删除的时间'
    },
    
    createAt: {
        type: Date,
        default: Date.now,
        index: true,
        description: '点赞记录的创建时间'
    },
    
    updateAt: {
        type: Date,
        default: Date.now,
        description: '点赞记录的最后更新时间'
    },
    
    ip: {
        type: String,
        default: '',
        description: '点赞用户的IP地址，用于防刷和统计分析'
    }
});

// 复合索引
likesSchema.index({ userId: 1, targetType: 1, targetId: 1 }, { unique: true });
likesSchema.index({ targetType: 1, targetId: 1, likeStatus: 1 });
likesSchema.index({ userId: 1, createAt: -1 });

// 自动更新updateAt字段
likesSchema.pre('save', function(next) {
    this.updateAt = new Date();
    next();
});

// 自增likeId
likesSchema.pre('save', async function(next) {
    if (this.isNew) {
        try {
            const lastLike = await this.constructor.findOne({}, {}, { sort: { likeId: -1 } });
            this.likeId = lastLike ? lastLike.likeId + 1 : 1;
        } catch (error) {
            return next(error);
        }
    }
    next();
});

// 静态方法：点赞或取消点赞
likesSchema.statics.toggleLike = async function(userId, targetType, targetId, likeStatus = 1, ip = '') {
    try {
        // 查找现有记录
        const existingLike = await this.findOne({
            userId,
            targetType,
            targetId,
            isDeleted: false
        });

        if (existingLike) {
            if (existingLike.likeStatus === likeStatus) {
                // 如果状态相同，则取消点赞
                existingLike.likeStatus = 0;
                existingLike.updateAt = new Date();
                await existingLike.save();
                return { success: true, action: 'cancelled', like: existingLike };
            } else {
                // 更新点赞状态
                existingLike.likeStatus = likeStatus;
                existingLike.updateAt = new Date();
                await existingLike.save();
                return { success: true, action: 'updated', like: existingLike };
            }
        } else {
            // 创建新的点赞记录
            const newLike = new this({
                userId,
                targetType,
                targetId,
                likeStatus,
                ip
            });
            await newLike.save();
            return { success: true, action: 'created', like: newLike };
        }
    } catch (error) {
        return { success: false, message: error.message };
    }
};

// 静态方法：获取点赞状态
likesSchema.statics.getLikeStatus = async function(userId, targetType, targetId) {
    try {
        const like = await this.findOne({
            userId,
            targetType,
            targetId,
            isDeleted: false
        });
        
        return {
            success: true,
            status: like ? like.likeStatus : 0,
            like: like
        };
    } catch (error) {
        return { success: false, message: error.message };
    }
};

// 静态方法：批量获取点赞状态
likesSchema.statics.batchGetLikeStatus = async function(userId, targetType, targetIds) {
    try {
        const likes = await this.find({
            userId,
            targetType,
            targetId: { $in: targetIds },
            isDeleted: false
        });
        
        const statusMap = {};
        targetIds.forEach(id => {
            statusMap[id] = 0; // 默认未点赞
        });
        
        likes.forEach(like => {
            statusMap[like.targetId] = like.likeStatus;
        });
        
        return { success: true, statusMap };
    } catch (error) {
        return { success: false, message: error.message };
    }
};

// 静态方法：获取目标的点赞统计
likesSchema.statics.getLikeStats = async function(targetType, targetId) {
    try {
        const stats = await this.aggregate([
            {
                $match: {
                    targetType,
                    targetId,
                    isDeleted: false
                }
            },
            {
                $group: {
                    _id: '$likeStatus',
                    count: { $sum: 1 }
                }
            }
        ]);
        
        const result = {
            likes: 0,      // 点赞数
            dislikes: 0,   // 点踩数
            total: 0       // 总互动数
        };
        
        stats.forEach(stat => {
            if (stat._id === 1) {
                result.likes = stat.count;
            } else if (stat._id === -1) {
                result.dislikes = stat.count;
            }
        });
        
        result.total = result.likes + result.dislikes;
        
        return { success: true, stats: result };
    } catch (error) {
        return { success: false, message: error.message };
    }
};

// 静态方法：获取用户的点赞历史
likesSchema.statics.getUserLikeHistory = async function(userId, targetType = null, page = 1, limit = 20) {
    try {
        const skip = (page - 1) * limit;
        const query = {
            userId,
            likeStatus: 1, // 只获取点赞的记录
            isDeleted: false
        };
        
        if (targetType) {
            query.targetType = targetType;
        }
        
        const likes = await this.find(query)
            .sort({ createAt: -1 })
            .skip(skip)
            .limit(limit);
            
        const total = await this.countDocuments(query);
        
        return {
            success: true,
            likes,
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        };
    } catch (error) {
        return { success: false, message: error.message };
    }
};

// 静态方法：获取热门内容（按点赞数排序）
likesSchema.statics.getPopularContent = async function(targetType, timeRange = 7, limit = 20) {
    try {
        const startDate = new Date();
        startDate.setDate(startDate.getDate() - timeRange);
        
        const popular = await this.aggregate([
            {
                $match: {
                    targetType,
                    likeStatus: 1,
                    isDeleted: false,
                    createAt: { $gte: startDate }
                }
            },
            {
                $group: {
                    _id: '$targetId',
                    likeCount: { $sum: 1 },
                    latestLike: { $max: '$createAt' }
                }
            },
            {
                $sort: { likeCount: -1, latestLike: -1 }
            },
            {
                $limit: limit
            }
        ]);
        
        return { success: true, popular };
    } catch (error) {
        return { success: false, message: error.message };
    }
};

// 静态方法：删除点赞记录
likesSchema.statics.deleteLike = async function(userId, targetType, targetId) {
    try {
        const like = await this.findOne({
            userId,
            targetType,
            targetId,
            isDeleted: false
        });
        
        if (!like) {
            return { success: false, message: '点赞记录不存在' };
        }
        
        like.isDeleted = true;
        like.deletedAt = new Date();
        like.updateAt = new Date();
        await like.save();
        
        return { success: true, message: '删除成功' };
    } catch (error) {
        return { success: false, message: error.message };
    }
};

// 实例方法：获取安全的JSON数据
likesSchema.methods.getSafeJSON = function() {
    const obj = this.toObject();
    delete obj._id;
    delete obj.__v;
    return obj;
};

// 创建模型
const Likes = mongoose.model('Likes', likesSchema);

module.exports = Likes;